package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.MyEnum.MessageEnum;
import com.sky.annotation.PublicFill;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.enumeration.OperationType;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.vo.EmployeeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.Optional;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService{

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
//        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        /*if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageEnum.ACCOUNT_NOT_FOUND.getExplain());
        }*/

        //用mp和optional查询和判空
        Employee employee =
                Optional
                .ofNullable(
                getOne(new LambdaQueryWrapper<Employee>().eq(!username.isEmpty(), Employee::getUsername, username)))
                .orElseThrow(() -> new AccountNotFoundException(MessageEnum.ACCOUNT_NOT_FOUND.getExplain()));

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //将前端传来的明文密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageEnum.PASSWORD_ERROR.getExplain());
        }

        if (employee.getStatus() == StatusConstant.DISABLE.getNum()) {
            //账号被锁定
            throw new AccountLockedException(MessageEnum.ACCOUNT_LOCKED.getExplain());
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * @新增员工
     * @param employeeDTO
     */
    @Override
    @PublicFill(OperationType.INSERT)
    public void save(EmployeeDTO employeeDTO) {

        Employee employee = new Employee();

        //利用SpringBean提供的工具类  --> 进行对象拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        //设置账号的状态
        employee.setStatus(StatusConstant.ENABLE.getNum());

        //设置密码, 默认123456 --> 进行加密
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //设置当前记录的创建时间和修改时间
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());

        // TODO: 2023/7/10 后期需要修改
        //设置当前记录创建人id和修改人id
        //employee.setCreateUser(BaseContext.getCurrentId());
        //employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.insertByEmployee(employee);

        //mp替代

        save(employee);


    }

    /**
     * 分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {

        //使用分页插件
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        //使用mp代替
//        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);
        Page<Employee> page = new Page<>();

        //使用mp化简查询
        page.addAll(lambdaQuery()
                .like(employeePageQueryDTO.getName() != null && !employeePageQueryDTO.getName().isEmpty(), Employee::getName, employeePageQueryDTO.getName())
                .list());

        //封装返回视图对象
        return new PageResult(page.getTotal(), BeanUtil.copyToList(page.getResult(), EmployeeVO.class));
    }

    /**
     * 启用禁用员工账号
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //@Builder --> 创建实体类对象,并赋值
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();

        employeeMapper.update(employee);

    }

    /**
     * @根据id查询员工信息
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {

        Employee employee = employeeMapper.getById(id);

        employee.setPassword("*****");

        return employee;
    }

    /**
     * @编辑员工信息
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {

        Employee employee = new Employee();

        //对象拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.update(employee);

    }


}
